<?php

/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\mobile\controller;


use app\admin\model\ActivityConsumer;
use app\admin\model\ActivityInvitationLog;
use app\admin\model\CouponConsumer;
use app\admin\model\DonateLog;
use app\admin\model\Order;
use app\admin\model\Platform;
use app\admin\model\StoreAccount;
use app\admin\model\StoreJoinActivity;
use app\admin\model\template\ClaimConsume;
use app\admin\model\TicketConsumer;
use app\admin\model\WriteLog;
use app\BaseController;
use think\App;


/**
 * 用户操作
 *
 * @author Administrator
 *
 */
class Consumer extends BaseController
{

    public function saveStoreConsumer(){
        $request = $this->request;
        $param = $request->param();
        $StoreConsumerModel  =  new \app\admin\model\Consumer();
        $storeModel  = new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' =>$param['store_id'] ])->find();
        if ( $storeInfo['is_application'] != 2){
            return result(-1, '店铺未进件');
        }
        $StoreConsumerData = [
            'uid' => $param['uid'],
           // 'name' => $param['name'],
            'price' => $param['price'],
            'deductible_amount' => isset($param['deductible_amount'])?$param['deductible_amount']:0,
            'satisfy_amount' => isset($param['satisfy_amount'])?$param['satisfy_amount']:0,
            'store_id' => $param['store_id'],
            'expire_time' => $param['expire_time'],
            'type' => 2,
            'status' => 1,
            'platform_id'=>  $request->platform_id,
            'issue_type' => $param['issue_type'],
            'title' => isset($param['title'])?$param['title']:0,
            'goods_img' => isset($param['goods_img'])?$param['goods_img']:0,
            'consumer_type' => $param['consumer_type'],
           'collection_count' =>  isset($param['collection_count'])  && $param['collection_count']? $param['collection_count']:0,

           // 'provide_number' => $param['provide_number'],
         //   'surplus_number' => $param['surplus_number'],

        ];
        if (isset($param['id']) && $param['id']){
            $StoreConsumerModel->where(['id' => $param['id']])->update($StoreConsumerData);
            return result(0, '修改成功');
        }else{
            $StoreConsumerModel->save($StoreConsumerData);
            return result(0, '添加成功');
        }



    }

    public function consumerList(){
        $request = $this->request;
        $param = $request->param();
        $where[] = ['consumer.is_delete','=',0];
        $where[] = ['type','=',2];
        $where[] = ['platform_id','=', $request->platform_id];
        $where[]= ['platformInfo.expiration_time','>',time()];

        if (isset( $param['store_id'])  && $param['store_id']){
            $where[] = ['store_id','=',$param['store_id']];
        }

        if (isset( $param['is_expire'])  && $param['is_expire']){
            $where[] = ['expire_time','>=',time()];
        }
        if (isset( $param['status'])  && $param['status']){
            $where[] = ['consumer.status','=',$param['status']];
        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $SponsorConsumer = new \app\admin\model\Consumer();
        $total = $SponsorConsumer
            ->withJoin(['platformInfo'], 'LEFT')
            ->where($where)->count();

        if ($total) {
            $list = $SponsorConsumer
                ->withJoin(['platformInfo'], 'LEFT')
                ->where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
            foreach ($list as $key =>  $value){
                if ($value['type'] == 1){
                    $list[$key]['expire_time'] =  date('Y-m-d ',$value['expire_time']);
                }else{
                    $list[$key]['expire_time'] =  $value['expire_time'].'天';
                }

            }

        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function updateConsumer(){
        $request = $this->request;
        $param = $request->param();
        $consumerModel  =  new \app\admin\model\Consumer();
        $data =[
            'reason'=>  isset($param['reason'])? $param['reason']:'',
            'status' => $param['status']
        ];
        $consumerModel->where(['id'=> $param['id']])->update($data);
        return result(0, '修改成功');
    }

    public function delConsumer(){
        $request = $this->request;
        $param = $request->param();
        $SponsorConsumerModel = new \app\admin\model\Consumer();
        $id = $param['id'];
        //$id = explode(',',$param['id']);
        $row = $SponsorConsumerModel->whereIn('id', $id)->update(['is_delete' => 1]);

        return result(0, '删除成功');
    }

    public function sendUserConsumer(){
        $request = $this->request;
        $param = $request->param();
        $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
        $data = [];
        foreach ($param['send_uid'] as $value){
            $StoreConsumerModel  =  new \app\admin\model\Consumer();
            $ConsumerInfo  = $StoreConsumerModel->where(['id' => $param['id']])->find();
            $data = [
                'order_number' =>    getPayNo('csm'),
                'consumer_id' => $param['id'],
                'store_id' => $param['store_id'],
                'uid' => $value,
                'type' => 2,
                'issue_type' => $ConsumerInfo['issue_type'],
                'consumer_type'=> $ConsumerInfo['consumer_type'],
                'satisfy_amount'=> $ConsumerInfo['satisfy_amount'],
                'deductible_amount'=> $ConsumerInfo['deductible_amount'],
                'expire_time' => time() + ($ConsumerInfo['expire_time'] *86400) ,
                'platform_id' =>  $request->platform_id,
                'send_way' => 2,
                'status' => 1,
                'price' => 0,
                'write_store_id' =>  $param['store_id'],
                'verification_code' =>consumerVerificationCode()

            ];
            $consumerClaimLogModel->save($data);
            $settlement_code  = common_qr_code($consumerClaimLogModel->id.'&'.'1','consumer',$request->platform_id);
            $consumerClaimLogModel->where(['id' => $consumerClaimLogModel->id])->update(['settlement_code' =>$settlement_code ]);

            $consumerModel = new \app\admin\model\Consumer();
            $donateLogModel  = new DonateLog();// 赠送记录
            $donateLogData =[
                'consumer_id' => $param['id'],
               /// 'account_id' => $param['account_id'],
                'uid' => $value,
                'operation_uid' => $param['uid'],
                'claim_log' => $consumerClaimLogModel->id,
                'consumer_type'=> $ConsumerInfo['consumer_type'],
                'satisfy_amount' => $ConsumerInfo['satisfy_amount'],
            ];
            $donateLogModel->save($donateLogData);
            $consumerModel->where(['id' => $value])->inc('claimed_number')->update();
        }
        return result(0, '赠送成功');
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    // 领取店铺优惠券
    public function claimConsumer(){
        $request = $this->request;
        $param = $request->param();
        $consumerModel  =  new \app\admin\model\Consumer();
        $ConsumerInfo  = $consumerModel->where(['id' => $param['id']])->find();
        $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();

        $consumerClaimLogCount= $consumerClaimLogModel->where(['consumer_id' => $param['id'],'uid' => $param['uid']])->count();
        if ($consumerClaimLogCount){
            if ($ConsumerInfo['collection_count'] != 0 &&  $ConsumerInfo['collection_count'] >  $consumerClaimLogCount ){
                if ($ConsumerInfo['price'] > 0){
                    return result(-1, '购买次数已到上限');
                }else{
                    return result(-1, '领取次数已到上限');
                }

            }

        }
        $data  = [
            'order_number' =>    getPayNo('csm'),
            'consumer_id' => $param['id'],
            'store_id' => $ConsumerInfo['store_id'],
            'platform_id' =>  $request->platform_id,
            'price' => $ConsumerInfo['price'],
            'uid'  => $param['uid'],
            'expire_time' => time()+ ($ConsumerInfo['expire_time'] *86400 ),
            'type' => $ConsumerInfo['type'],
            'consumer_type'=> $ConsumerInfo['consumer_type'],
            'satisfy_amount' => $ConsumerInfo['satisfy_amount'],
            'deductible_amount' => $ConsumerInfo['deductible_amount'],
            'send_way' =>2,
            'way_code'  => $param['way_code'],
            'issue_type' => $ConsumerInfo['issue_type'],
            'write_store_id' =>  $ConsumerInfo['store_id'],
            'verification_code' =>consumerVerificationCode(),
        ];
//        if ($ConsumerInfo['provide_number'] >0){
//            if ( $ConsumerInfo['surplus_number'] == 0){
//                return result(-1, '优惠券已发放完');
//            }
//        }
        if ($ConsumerInfo['price'] > 0){
            $data['status']  = 0;
            $consumerClaimLogModel->save($data);
            $settlement_code  = common_qr_code($consumerClaimLogModel->id.'&'.'1','consumer',$request->platform_id);
            $consumerClaimLogModel->where(['id' => $consumerClaimLogModel->id])->update(['settlement_code' =>$settlement_code ]);
            return result(0, '待支付',['id' => $consumerClaimLogModel->id,'code' => 1]);
        }else{
          $data['status']  = 1;


            $platformModel = new Platform();
            $platformInfo = $platformModel->where(['id' =>  $request->platform_id])->find();
            $templateModel   = new \app\admin\model\Template();
            $templateInfo = $templateModel->where(['name'=>'claim_consume',
                'platform_id'=> $request->platform_id])->find();
            if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
                $userModel = new \app\admin\model\User();
                $userInfo = $userModel->where(['id' => $param['uid']])->find();
                if ($userInfo['openid']){
                    $sendData = [
                        'template_id' => $templateInfo['template_id'],
                        'appid' => $platformInfo['xcx_appid'],
                        'appsecret' => $platformInfo['xcx_appsecret'],
                        'openid' => $userInfo['openid'],
                        'name' => '满'.$ConsumerInfo['satisfy_amount'].'减'.$ConsumerInfo['deductible_amount'],
                        'type_name' => '优惠券',
                    ];

                    if ($ConsumerInfo['issue_type'] == 1){
                        $sendData['name']  ='满'.$ConsumerInfo['satisfy_amount'].'减'.$ConsumerInfo['deductible_amount'];

                    }elseif($ConsumerInfo['issue_type'] == 2){
                        $sendData['name']  ='满'.$ConsumerInfo['satisfy_amount'].'折扣'.$ConsumerInfo['deductible_amount'].'%';

                    }else{
                        $sendData['name']  =$ConsumerInfo['title'];

                    }
                    $ClaimConsumeTemplate = new ClaimConsume();
                    $ClaimConsumeTemplate->send($sendData);
                }
            }
          
            $consumerClaimLogModel->save($data);
            $settlement_code  = common_qr_code($consumerClaimLogModel->id.'&'.'1','consumer',$request->platform_id);
            $consumerClaimLogModel->where(['id' => $consumerClaimLogModel->id])->update(['settlement_code' =>$settlement_code ]);


            $consumerModel->where(['id'=> $param['id']])->inc('claimed_number')->update();


            return result(0, '领取成功',['id' => $consumerClaimLogModel->id,'code' => 0]);
        }

    }

    // 领取活动优惠券
    public function claimActivityConsumer(){

        $request = $this->request;
        $param = $request->param();
        $activityConsumerModel  =  new \app\admin\model\ActivityConsumer();
        $activityConsumerInfo  = $activityConsumerModel->where(['id' => $param['id']])->find();
        $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
        if ($activityConsumerInfo['claim_number'] != 0){
           if ( $activityConsumerInfo['surplus_number'] == 0){
               return result(-1, '此消费券已领完');
           }
        }
        if ($activityConsumerInfo['start_time']< time() &&$activityConsumerInfo['end_time']> time() ){
            $activityModel  =  new \app\admin\model\Activity();
            $activityInfo = $activityModel->where(['id' => $activityConsumerInfo['activity_id']])->find();
            $uidClaimCount =  $consumerClaimLogModel->where([
                   'activity_id' => $activityConsumerInfo['activity_id'],

                   'uid' =>$param['uid']])->where('status','<>',0)->count();
            $activityInvitationLogInfo = [];
            $activityInvitationLogModel = new ActivityInvitationLog();
            if ($activityInfo['total_claim_number']  > 0 && $activityInfo['total_claim_number']  <= $uidClaimCount){
                $activityInvitationLogInfo =  $activityInvitationLogModel
                    ->where([
                        'activity_id' => $activityConsumerInfo['activity_id'] ,
                        'sent_uid'=> $param['uid'],
                    ])->where('surplus_number','>',0)->find();
               if ( empty($activityInvitationLogInfo) ){
                   return result(-1, '此活动参与已上限');
               }
            }
            $consumerModel = new \app\admin\model\Consumer();
            $ConsumerInfo =  $consumerModel->where(['id' => $activityConsumerInfo['consumer_id'] ])->find();
            $data  = [
                'order_number' =>    getPayNo('csm'),
                'consumer_id' => $activityConsumerInfo['consumer_id'],
                'activity_consumer_id' => $param['id'],
                'platform_id' =>  $request->platform_id,
                'price' => $ConsumerInfo['price'],
                'uid'  => $param['uid'],
                'expire_time' => $ConsumerInfo['expire_time'],
                'activity_id' => $activityConsumerInfo['activity_id'],
                'type' => $ConsumerInfo['type'],
                'consumer_type'=> $ConsumerInfo['consumer_type'],
                'satisfy_amount' => $ConsumerInfo['satisfy_amount'],
                'deductible_amount' => $ConsumerInfo['deductible_amount'],
                'invitation_uid' => isset($param['invitation_uid'])?$param['invitation_uid']:0,
                'send_way' =>1,
                'way_code'  =>'WX_LITE',
                'issue_type' => $ConsumerInfo['issue_type'],
                'verification_code' =>consumerVerificationCode()
            ];
            if ($ConsumerInfo['price'] > 0){
                $data['status']  = 0;

                $consumerClaimLogModel->save($data);
                $settlement_code  = common_qr_code($consumerClaimLogModel->id.'&'.'1','consumer', $request->platform_id);
                $consumerClaimLogModel->where(['id' => $consumerClaimLogModel->id])->update(['settlement_code' =>$settlement_code ]);

                return result(0, '待支付',['id' => $consumerClaimLogModel->id,'code'=> 1]);
            }else{
                $data['status']  = 1;
                $consumerClaimLogModel->save($data);
                $settlement_code  = common_qr_code($consumerClaimLogModel->id.'&'.'1','consumer', $request->platform_id);
                $consumerClaimLogModel->where(['id' => $consumerClaimLogModel->id])->update(['settlement_code' =>$settlement_code ]);

                if ( $activityConsumerInfo['claim_number'] >0){
                    $activityConsumerModel->where(['id' => $param['id']])
                        ->dec('surplus_number')->inc('claimed_number')
                        ->update();
                }else{
                    $activityConsumerModel->where(['id' => $param['id']])
                       ->inc('claimed_number')
                        ->update();
                }
                if ($activityInvitationLogInfo){
                    $activityInvitationLogModel->where(['id' => $activityInvitationLogInfo['id']])
                        ->dec('surplus_number')->update();
                }
                $consumerModel->where(['id'=> $activityConsumerInfo['consumer_id']])->inc('claimed_number')->update();
                if ( isset($param['invitation_uid']) && $param['invitation_uid']){
                    $activityInvitationLogModel->save([
                        'sent_uid' => $param['invitation_uid'],
                        'uid' => $param['uid'],
                        'activity_id' => $param['activity_id'],
                        'claim_number' => $activityInfo['invitation_obtain_frequency'],
                        'surplus_number' => $activityInfo['invitation_obtain_frequency'],
                    ]);
                }
                $activityModel->where(['id' => $activityInfo['id']])->inc('claimed_number')->update();
                $ClaimConsumeTemplate = new ClaimConsume();
                $platformModel = new Platform();
                $platformInfo = $platformModel->where(['id' => $request->platform_id])->find();
                $templateModel   = new \app\admin\model\Template();
                $templateInfo = $templateModel->where(['name'=>'claim_consume',
                    'platform_id'=>$request->platform_id ])->find();
                $userModel = new \app\admin\model\User();
                $userInfo = $userModel->where(['id' => $param['uid']])->find();
                if ( $userInfo['openid']){
                    if (isset($templateInfo['template_id']) && $templateInfo['template_id']) {
                        $sendData = [
                            'template_id' => $templateInfo['template_id'],
                            'appid' => $platformInfo['xcx_appid'],
                            'appsecret' => $platformInfo['xcx_appsecret'],
                            'openid' => $userInfo['openid'],
                            'name' => '满' . $ConsumerInfo['satisfy_amount'] . '减' . $ConsumerInfo['deductible_amount'],
                            'type_name' => '消费券',
                        ];

                        if ($ConsumerInfo['issue_type'] == 1) {
                            $sendData['name'] = '满' . $ConsumerInfo['satisfy_amount'] . '减' . $ConsumerInfo['deductible_amount'];

                        } elseif ($ConsumerInfo['issue_type'] == 2) {
                            $sendData['name'] = '满' . $ConsumerInfo['satisfy_amount'] . '折扣' . $ConsumerInfo['deductible_amount'] . '%';

                        } else {
                            $sendData['name'] = $ConsumerInfo['title'];

                        }
                        $ClaimConsumeTemplate->send($sendData);
                    }
                }
                return result(0, '领取成功',['id' => $consumerClaimLogModel->id,'code'=> 0]);
            }
        }else{
            return result(-1, '此消费券不在领取时间范围');
        }

    }


    public function claimConsumerLog(){
        $request = $this->request;
        $param = $request->param();
        $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $where[] = ['consumer_claim_log.platform_id'  ,'=',  $request->platform_id];
        $StoreJoinActivityModel =  new StoreJoinActivity();

        if (isset($param['send_way']) &&  $param['send_way']){

            $where[] = ['consumer_claim_log.send_way'  ,'=',$param['send_way']];

        }

        if (isset($param['ticket_id']) &&  $param['ticket_id']){

            $where[] = ['consumer_claim_log.ticket_id'  ,'=',$param['ticket_id']];

        }

        if (isset($param['coupon_id']) &&  $param['coupon_id']){

            $where[] = ['consumer_claim_log.coupon_id'  ,'=',$param['coupon_id']];

        }

        $store_id = 0;
        $activityId =[];
        if ( isset($param['store_id']) &&  $param['store_id']){
            $store_id =  $param['store_id'];
            $StoreJoinActivityList = $StoreJoinActivityModel
                ->where(['store_id' => $param['store_id']])->select()->toArray();
            if ($StoreJoinActivityList){
                $activityId = array_column($StoreJoinActivityList,'activity_id');
            }
        }
        if ( isset($param['write_store_id']) &&  $param['write_store_id']){
            $where[] = ['consumer_claim_log.write_store_id'  ,'=',$param['write_store_id']];

        }
        if (isset($param['consumer_type']) && $param['consumer_type']){
            $where[] = ['consumer_claim_log.consumer_type'  ,'in', [0,$param['consumer_type']]];
        }
        if (isset($param['uid']) && $param['uid']){
            $where[] = ['consumer_claim_log.uid'  ,'=', $param['uid']];
        }
        if (isset($param['type']) && $param['type']){
            $where[] = ['consumer_claim_log.type'  ,'=', $param['type']];
        }

        if (isset($param['status']) && $param['status'] >0){
            if ($param['status'] ==  1 || $param['status']  == 2 ){
                $where[] = ['consumer_claim_log.status'  ,'=', $param['status']];
            }else{
                $where[] = ['consumer_claim_log.status'  ,'=', 1];
                $where[] = ['consumer_claim_log.expire_time'  ,'<', time()];
            }

        }else{
            $where[] = ['consumer_claim_log.status'  ,'in', [1,2]];
        }

        $total  = $consumerClaimLogModel
            ->withJoin([
                'storeInfo',
            ], 'LEFT')
            ->where($where)
            ->where(function ( $query) use ($store_id,$activityId) {
                if ($store_id){
                    $query->where(['store_id'=>$store_id ]);
                    if ($activityId){
                        $query->whereOr('activity_id','in',$activityId);
                    }
                }
            })
            ->count();

       $list =  $consumerClaimLogModel
            ->where($where)
           ->withJoin([
               'storeInfo',
           ], 'LEFT')
           ->where(function ( $query) use ($store_id,$activityId) {
               if ($store_id){
                   $query->where(['store_id'=>$store_id ]);
                   if ($activityId){
                       $query->whereOr('activity_id','in',$activityId);
                   }
               }

           })->limit(($pindex - 1) * $psize, $psize)
           ->order('consumer_claim_log.create_time','desc')->select();
       //echo  $consumerClaimLogModel->getLastSql();exit;
       foreach ($list  as $key => $value){
           $consumerModel  =  new \app\admin\model\Consumer();
           $consumerInfo =   $consumerModel->where(['id' => $value['consumer_id']])->find();
           $list[$key]['consumer_info'] = $consumerInfo;
           if ($value['status'] == 1  && $value['expire_time'] < time() ){
               $list[$key]['status'] =3;
           }
           $list[$key]['expire_time'] = date('Y-m-d',$value['expire_time']);
           $list[$key]['ticket_info'] = [];
           $list[$key]['coupon_info'] = [];
           if ($value['ticket_id']){
              $ticketModel =  new \app\admin\model\Ticket();
               $list[$key]['ticket_info']  =$ticketModel ->where(['id' => $value['ticket_id']])->find();

           }
           if ($value['coupon_id']){
               $CouponModel =  new \app\admin\model\Coupon();
               $list[$key]['coupon_info']  =$CouponModel ->where(['id' => $value['coupon_id']])->find();

           }
           if ($value['activity_id']){
               $CouponModel =  new \app\admin\model\Activity();
               $list[$key]['activity_info']  =$CouponModel ->where(['id' => $value['activity_id']])->find();

           }

       }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));

    }

    public  function consumerInfo(){
        $request = $this->request;
        $param = $request->param();
        $StoreConsumerModel  =  new \app\admin\model\Consumer();
        $StoreConsumerInfo = $StoreConsumerModel->where(['id' => $param['id']])->find();
        $storeModel = new \app\admin\model\Store();
        $storeInfo = $storeModel ->where(['id' => $StoreConsumerInfo['store_id']])->find();
        $StoreConsumerInfo['store_info'] = $storeInfo;
        if ($StoreConsumerInfo['type'] == 1){
            $StoreConsumerInfo['expire_time'] =  date('Y-m-d ',$StoreConsumerInfo['expire_time']);
        }else{
            $StoreConsumerInfo['expire_time'] =  $StoreConsumerInfo['expire_time'];
        }

        $StoreConsumerInfo['is_claim'] = 0;
        if (isset($param['uid']) && $param['uid']){
            $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
            $consumerClaimLogInfo = $consumerClaimLogModel->where(['uid' =>$param['uid'],'consumer_id'  => $param['id']])->where('status','<>',0)->find();
            if ($consumerClaimLogInfo){
                $StoreConsumerInfo['is_claim'] = 1;
            }
        }
        $activityConsumerModel =  new ActivityConsumer();
        $activityConsumerInfo =  $activityConsumerModel->where(['consumer_id' => $param['id']])->find();
        $StoreConsumerInfo['activity_info'] = [];
        if ($activityConsumerInfo){
            $activityModel = new \app\admin\model\Activity();
            $activityInfo =  $activityModel->where(['id' => $activityConsumerInfo['activity_id']])->find();
            $StoreConsumerInfo['activity_info']  =$activityInfo;
        }

        $CouponConsumerModel =  new CouponConsumer();
        $CouponConsumerInfo =  $CouponConsumerModel->where(['consumer_id' => $param['id']])->find();
        $StoreConsumerInfo['coupon_info'] = [];
        if ($CouponConsumerInfo){
            $CouponModel = new \app\admin\model\Coupon();
            $couponInfo =  $CouponModel->where(['id' => $CouponConsumerInfo['coupon_id']])->find();
            $StoreConsumerInfo['coupon_info']  =$couponInfo;
        }

        $ticketConsumerModel =  new TicketConsumer();
        $ticketConsumerInfo =  $ticketConsumerModel->where(['consumer_id' => $param['id']])->find();
        $StoreConsumerInfo['ticket_info'] = [];
        if ($ticketConsumerInfo){
            $ticketModel = new \app\admin\model\Ticket();
            $ticketInfo =  $ticketModel->where(['id' => $CouponConsumerInfo['ticket_id']])->find();
            $StoreConsumerInfo['ticket_info']  =$ticketInfo;
        }


        return result(0, '优惠券详情',$StoreConsumerInfo);
    }


    public function settlementConsumer(){
        $request = $this->request;
        $param = $request->param();
        if (isset($param['verification_code']) && $param['verification_code']){
            $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
            $consumerClaimLogInfo = $consumerClaimLogModel->where(['verification_code' => $param['verification_code']])->find();
        }else{
            $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
            $consumerClaimLogInfo = $consumerClaimLogModel->where(['id' => $param['id']])->find();
        }
        $storeAccount = new StoreAccount();
        $storeAccountInfo  =$storeAccount->where(['id' => $param['account_id']])->find();
        if ($consumerClaimLogInfo['expire_time'] < time()){
            return result(0, '此券已过期',[]);
        }
        if ($consumerClaimLogInfo['store_id']){
            if ($storeAccountInfo['store_id'] !=$consumerClaimLogInfo['store_id'] ){
                return result(0, '此优惠券不属于本店',[]);
            }
        }
        if ($consumerClaimLogInfo['activity_id']){
            $storeJoinAccount = new StoreJoinActivity();
            $storeJoinInfo  = $storeJoinAccount->where(['store_id' => $storeAccountInfo['store_id'],'activity_id' => $consumerClaimLogInfo['activity_id']])->find();


            if (empty($storeJoinInfo)){
                return result(0, '本店铺未参与此活动，该券无法使用',[]);
            }
        }
        $consumerModel  =  new \app\admin\model\Consumer();
        $consumerInfo =   $consumerModel->where(['id' => $consumerClaimLogInfo['consumer_id']])->find();
        $consumerClaimLogModel->where(['id' => $param['id']])->update(['status' => 2,'write_store_id'=> $storeAccountInfo['store_id']]);
        $mchOrderNo =    getPayNo('con');
        $data = [
            'uid' => $consumerClaimLogInfo['uid'],
            'store_id' =>  $storeAccountInfo['store_id'],
            'platform_id'  => isset($consumerClaimLogInfo['platform_id'])? $consumerClaimLogInfo['platform_id'] : 0 ,
            'activity_id'  => isset($consumerClaimLogInfo['activity_id'])? $consumerClaimLogInfo['activity_id'] : 0 ,
            'total_amount' =>  0,
            'consumer_claim_log' =>  $param['id'],
            'consumer_id' =>  $consumerClaimLogInfo['consumer_id'],
         //   'deductible_amount' =>0,
            'pay_amount' => 0,
            'consumer_type' =>  $consumerClaimLogInfo['consumer_type'],
            'order_number' => $mchOrderNo,
            'type'  => isset($consumerClaimLogInfo['type'])? $consumerClaimLogInfo['type'] : 0 ,
            'subsidy_status' => 0,
            'issue_type' => isset($consumerClaimLogInfo['issue_type'])? $consumerClaimLogInfo['issue_type'] : 0 ,
            'account_id' => $param['account_id'],
            'operation_uid' => $param['operation_uid'],
            'write_type' =>  2 ,
            'send_way' => isset($consumerClaimLogInfo['send_way'])? $consumerClaimLogInfo['send_way'] : 0 ,

        ];

        if ($consumerInfo['issue_type'] == 1){
           // $amount = bcsub( $param['amount'],$consumerInfo['deductible_amount'],2);
            $deductible_amount  = $consumerInfo['deductible_amount'];
        }elseif ($consumerInfo['issue_type'] == 2){
            $deductible_amount = bcmul( $consumerInfo['satisfy_amount'],$consumerInfo['deductible_amount']/100,2);
        }else{
            $deductible_amount  =0;
        }
        $data['deductible_amount'] = $deductible_amount;
        $data['subsidy_amount'] = 0;
        if ($consumerInfo){
            if ($consumerInfo['store_undertake_proportion'] > 0){
                // 平台补贴
                 $subsidy_amount = bcdiv(bcmul( $deductible_amount, $consumerInfo['store_undertake_proportion'],2),100,2);

                $undertake_amount  = bcsub($deductible_amount,$subsidy_amount,2);
                $data['undertake_proportion']  = $consumerInfo['store_undertake_proportion'];
                $data['undertake_amount']  =  $undertake_amount;
                $data['subsidy_amount']  = $subsidy_amount;
            }else{
                $data['undertake_proportion']  = 0;
                $data['undertake_amount']  = $deductible_amount;
                $data['subsidy_amount']  = 0;
            }
        }
        if ( $data['subsidy_amount']> 0){
            $data['subsidy_status']  = 1;
        }else{
            $data['subsidy_status']  = 0;
        }
        if ($data['activity_id']){
            $activityModel = new \app\admin\model\Activity();
            $activityModel->where(['id' =>$data['activity_id'] ])->inc('cancel_number')->update();
        }

        $orderModel =  new WriteLog();
        $orderModel->save($data);
        return result(0, '核销成功',[]);
    }

    public function claimConsumerInfo(){
        $request = $this->request;
        $param = $request->param();

        if (isset($param['id']) &&$param['id']  ){
            $where =['consumer_claim_log.id' => $param['id']];
        }else{
            $where =['consumer_claim_log.verification_code' => $param['verification_code']];
        }
        $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
        $consumerClaimInfo  = $consumerClaimLogModel ->withJoin([
            'storeInfo',
        ], 'LEFT')->where($where)->find();
        if (empty($consumerClaimInfo)){
            return result(-1, '数据不存在');
        }
        $consumerModel  =  new \app\admin\model\Consumer();
        $consumerInfo =   $consumerModel->where(['id' => $consumerClaimInfo['consumer_id']])->find();
        $consumerClaimInfo['consumer_info'] = $consumerInfo;

        if ( $consumerClaimInfo['status'] == 1 &&  $consumerClaimInfo['expire_time'] < time()){
            $consumerClaimInfo['status']  = 3;
        }
        $consumerClaimInfo['expire_time'] = date('Y-m-d',$consumerClaimInfo['expire_time']);
        $consumerClaimInfo['ticket_info'] = [];
        $consumerClaimInfo['coupon_info'] = [];
        if ($consumerClaimInfo['ticket_id']){
            $ticketModel =  new \app\admin\model\Ticket();
            $consumerClaimInfo ['ticket_info']  =$ticketModel ->where(['id' => $consumerClaimInfo['ticket_id']])->find();

        }
        if ($consumerClaimInfo['coupon_id']){
            $CouponModel =  new \app\admin\model\Coupon();
            $consumerClaimInfo['coupon_info']  =$CouponModel ->where(['id' => $consumerClaimInfo['coupon_id']])->find();

        }

        if ($consumerClaimInfo['activity_id']){
            $ActivityModel =  new \app\admin\model\Activity();
            $consumerClaimInfo['activity_info']  = $ActivityModel ->where(['id' => $consumerClaimInfo['activity_id']])->find();

        }
        return result(0, '优惠券详情',$consumerClaimInfo);
    }












}